declare namespace g = "ddi:group:3_1";
declare namespace d = "ddi:datacollection:3_1";
declare namespace r = "ddi:reusable:3_1";

import module namespace request="http://exist-db.org/xquery/request";
import module namespace json="http://www.json.org";

declare option exist:serialize "method=text media-type=application/json";

(: if callback is defined :)
let $callback := request:get-parameter("callback", ())
let $lang := request:get-parameter("lang", ())

let $s := request:get-parameter("s", ())

let $start := xs:integer(request:get-parameter("start", "0"))
let $records := xs:integer(request:get-parameter("records", "10"))
let $action := request:get-parameter("action","search")

let $result :=
	if(empty($lang))
	then
		collection('/db/qb')//d:QuestionItem[ft:query(d:QuestionText, $s)]
	else
		collection('/db/qb')//d:QuestionItem[ft:query(d:QuestionText[@xml:lang=$lang], $s)]

(: compute the limits for this page :)
let $max := count($result)
let $start := 
      if ($action = "previous") 
      then max(($start - $records, 1))
      else if ($action="next")
      then  if ($max <$start +$records) 
            then $start 
            else $start +$records
      else if ($action="Search")
      then 1
      else $start
let $end :=  min (($start + $records ,$max))
 
(: restrict the full set of matches to this subsequence :)
let $matches := subsequence($result,$start,($end+1))

let $all := count(collection('/db/qb')//d:QuestionItem)

let $output := <result>
					<total>{$all}</total>
					<hits>{$max}</hits>
					<start>{$start}</start>
					<end>{$end}</end>
					<questions>{$matches}</questions>
				</result>

return 
	if(empty($callback))
	then
		json:xml-to-json($output)
	else
		($callback, "(", json:xml-to-json($output),")")